package com.example.demo.controller;

import cn.hutool.core.date.DateTime;
import com.example.demo.common.AjaxResult;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.Articleinfo;
import com.example.demo.entity.Userinfo;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/art")
public class ArticleController implements Serializable {

    @Resource
    private ArticleService articleService;

    //返回右侧文章信息
    @RequestMapping("/mylist")
    public AjaxResult getMyList(HttpServletRequest request){
        Userinfo userinfo= UserSessionUtils.getUser(request);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        List<Articleinfo> list=articleService.getMyList(userinfo.getId());
        for (Articleinfo articleinfo:list) {
            //截取100字以内的内容进行页面的展示
            if(articleinfo.getContent().length()>100)
            articleinfo.setContent(articleinfo.getContent().substring(0,100));
        }
        return AjaxResult.success(list);
    }

    //删除文章
    @RequestMapping("/del")
    public AjaxResult del(HttpServletRequest request,Integer id){
        if(id==null||id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        Userinfo userinfo=UserSessionUtils.getUser(request);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-1,"用户未登录");
        }
        return AjaxResult.success(articleService.del(id,userinfo.getId()));
    }

    //查看全文
    @RequestMapping("/detail")
    public AjaxResult getDetail(Integer id){
        if(id==null&&id<=0){
            return AjaxResult.fail(-1,"非法参数！");
        }
        return AjaxResult.success(articleService.getDetail(id));
    }

    //增加阅读量
    @RequestMapping("/incrementrcount")
    public AjaxResult incrementRCount(Integer id){
        if(id==null||id<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        return AjaxResult.success(articleService.increamentRCount(id));
    }

    //添加文章
    @RequestMapping("/add")
    public AjaxResult add(HttpServletRequest request,Articleinfo articleinfo){
        //非空校验
        if(articleinfo==null|| !StringUtils.hasLength(articleinfo.getTitle())|| !StringUtils.hasLength(articleinfo.getContent())){
            return AjaxResult.fail(-1,"非法参数");
        }
        //从登录状态得到用户uid
        Userinfo userinfo=UserSessionUtils.getUser(request);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-2,"用户未登陆");
        }
        //添加登陆状态的uid
        articleinfo.setUid(userinfo.getId());
        //返回数据库结果
        return AjaxResult.success(articleService.add(articleinfo));
    }

    //修改文章
    @RequestMapping("/update")
    public AjaxResult update(HttpServletRequest request,Articleinfo articleinfo){
        if(articleinfo==null||!StringUtils.hasLength(articleinfo.getTitle())|| !StringUtils.hasLength(articleinfo.getContent())
        || articleinfo.getId()==null){
            return AjaxResult.fail(-1,"非法参数");
        }
        Userinfo userinfo=UserSessionUtils.getUser(request);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-2,"用户未登陆");
        }
        //判断是否是发布文章的人来修改文章
        articleinfo.setUid(userinfo.getId());
        Timestamp timestamp=new Timestamp(System.currentTimeMillis());
//        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        format.format(timestamp);
        articleinfo.setUpdatetime(timestamp);
        return AjaxResult.success(articleService.update(articleinfo));
    }

    //分页显示文章列表页
    @RequestMapping("/listbypage")
    public AjaxResult getListByPage(Integer pindex,Integer psize){
        //1、参数校正
        if(pindex==null||pindex<=1){
            pindex=1;
        }
        if(psize==null||psize<=1){
            psize=3;
        }
        //分页的公式=（当前页面-1）*每页显示条数
        int offset=(pindex-1)*psize;
        List<Articleinfo> list=articleService.getListByPage(psize,offset);
        List<Userinfo> userinfolist=new ArrayList<>();
        //对文章中的数据进行0-100字符的分割，不显示全部内容
        for (Articleinfo articleinfo:list) {
            if (articleinfo.getContent().length() >= 100) {
                articleinfo.setContent(articleinfo.getContent().substring(0, 100));
            }
            //返回文章的作者
            userinfolist.add(articleService.userMapper.getUserById(articleinfo.getUid()));
        }
        //当前页面一共有多少页
        //a、总共有多少条数据
        int totalCount=articleService.getcount();
        //b、总条数/psize(每页显示条数）
        double pcountdb=totalCount / (psize*1.0);
        //c、使用进一法，得到页面的元素
        int pcount= (int)Math.ceil(pcountdb);
        //d、用hashmap封装元素返回给前端页面
        HashMap<String,Object> result=new HashMap<>();
        result.put("list",list);
        result.put("pcount",pcount);
        result.put("userinfolist",userinfolist);
        return AjaxResult.success(result);
    }

    //保存文章草稿
    @RequestMapping("/save")
    public AjaxResult addsave(HttpServletRequest request,Articleinfo articleinfo){
        //非空校验
        if(articleinfo==null||!StringUtils.hasLength(articleinfo.getTitle())||
                !StringUtils.hasLength(articleinfo.getContent())){
            return AjaxResult.fail(-1,"非法参数");
        }
        //从登录用户处获取id
        Userinfo userinfo=UserSessionUtils.getUser(request);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-1,"用户未登录！");
        }
        articleinfo.setUid(userinfo.getId());
        return AjaxResult.success(articleService.addsave(articleinfo));
    }

    //获取个人保存的所有文章
    @RequestMapping("/mylistsave")
    public AjaxResult getMyListSave(HttpServletRequest request){
        Userinfo userinfo= UserSessionUtils.getUser(request);
        if(userinfo==null||userinfo.getId()<=0){
            return AjaxResult.fail(-1,"非法参数");
        }
        List<Articleinfo> list=articleService.getMyListSave(userinfo.getId());
        for (Articleinfo articleinfo:list) {
            //截取100字以内的内容进行页面的展示
            if(articleinfo.getContent().length()>100)
                articleinfo.setContent(articleinfo.getContent().substring(0,100));
        }
        return AjaxResult.success(list);
    }

    // 根据文章标题或作者搜索文章
    @RequestMapping("/qrylist")
    public AjaxResult getSearch(Integer pindex, Integer psize, String title){
        //1、参数校正
        if(pindex==null||pindex<=1){
            pindex=1;
        }
        if(psize==null||psize<=1){
            psize=3;
        }
        //分页的公式=（当前页面-1）*每页显示条数
        int offset=(pindex-1)*psize;
        List<Articleinfo> list = articleService.getSearch(psize,offset,title);
        if(list.size() == 0){
            return AjaxResult.fail(-1,"你搜索的内容为空!");
        }
        List<Userinfo> userinfolist=new ArrayList<>();
        //对文章中的数据进行0-100字符的分割，不显示全部内容
        for (Articleinfo articleinfo1:list) {
            if (articleinfo1.getContent().length() >= 100) {
                articleinfo1.setContent(articleinfo1.getContent().substring(0, 100));
            }
            //返回文章的作者
            userinfolist.add(articleService.userMapper.getUserById(articleinfo1.getUid()));
        }
        //当前页面一共有多少页
        //a、总共有多少条数据
        int totalCount=articleService.getcount();
        //b、总条数/psize(每页显示条数）
        double pcountdb=totalCount / (psize*1.0);
        //c、使用进一法，得到页面的元素
        int pcount= (int)Math.ceil(pcountdb);
        //d、用hashmap封装元素返回给前端页面
        HashMap<String,Object> result=new HashMap<>();
        result.put("list",list);
        result.put("pcount",pcount);
        result.put("userinfolist",userinfolist);
        return AjaxResult.success(result);
    }
}
